//
//  YAEmoticonViewModel.swift
//  表情键盘[练习]
//
//  Created by 鱼龙之梦 on 15/9/12.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
//注意：用VM加载数据，要有个数组存数据
class YAEmoticonViewModel{
    
    /// 单例
    static let sharedEVM = YAEmoticonViewModel()
    private init (){
        loadPackages()
    }
    //添加最近的表情
    func favorite(indexPath:NSIndexPath)
    {
        if indexPath.section == 0{
            return
        }
        //获取表情符号
        let em = emoticon(indexPath)
        //var packages[0].emoticons = packages[0].emoticons
        em.times++
        if !packages[0].emoticons.contains(em){
            packages[0].emoticons.insert(em, atIndex: 0)
        }
        //按使用次数排序
        packages[0].emoticons.sortInPlace { $0.times > $1.times }
        //保证只显示一页，多余的删除掉
        if packages[0].emoticons.count>21{
            packages[0].emoticons.removeAtIndex(19)
        }
       // printLog(packages[0].emoticons as NSArray)
       // printLog(packages[0].emoticons.count)
    }
    lazy var packages = [YAEmoticonPackage]()
    //MARK:--- 根据给定的表情字符串，生成带表情的属性字符串
    func emoticonText(str:String,font:UIFont)->NSAttributedString{
       // printLog(str)
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: str.characters.count))
        var count = results.count
        let strM = NSMutableAttributedString(string: str)
        while count>0{
            let range = results[--count].rangeAtIndex(0)
            let chs = (str as NSString).substringWithRange(range)
            if let emoticon = emoticon(chs) {
                let imageText = YAEmoticonText.emoticonAttributeText(emoticon, font: font)
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
        }
        return strM
    }
    private func emoticon(str:String)->YAEmoticon?{
        var emoticon:YAEmoticon?
        for p in packages {
            emoticon = p.emoticons.filter(){$0.chs == str}.last
            if emoticon != nil {
                break
            }
        }
        return emoticon
    }
    func loadPackages(){
        //注意：添加分组
        packages.append(YAEmoticonPackage(keyedValues: ["group_name_cn":"最近Aa"]))
        //注意：获取数据源文件路径
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        //注意：用路径生成字典
        let dict = NSDictionary(contentsOfFile: path!)
        //注意：从字典中拿取表情数组
        let array = dict!["packages"] as![[String:AnyObject]]
        //注意：遍历表情数组 拿到各表情数组的路径
        for infoDict in array{
            let id = infoDict["id"] as! String
            let emPath = NSBundle.mainBundle().pathForResource("info.plist", ofType: nil, inDirectory: "Emoticons.bundle/" + id)
            
            //注意：将路径中的数据转成字典
            let packageDict = NSDictionary(contentsOfFile: emPath!) as! [String:AnyObject]
            //注意：转化为模型
            packages.append(YAEmoticonPackage(keyedValues: packageDict))
        }
        
    }
    func emoticon (indexPath:NSIndexPath)->YAEmoticon{
        return packages[indexPath.section].emoticons[indexPath.item]
    }
}
